var width = 800;
var height = 320;
var idOfCanvas = "canv";
var color_canvasBg = "#44D600";
var g;
var c;

$(document).ready(function() 
	{
	c = document.getElementById(idOfCanvas);

	if (!c) {
		alert("canvas element with id '" + idOfCanvas + "' not found");
	}
	ctx = c.getContext('2d');

	c.width = width;
	c.height = height;
	
	c.addEventListener("click", gameOnClick, false);
	
	g = new Game();
	g.setContext(ctx);
	
	for(i = 0; i < 10; i++)
	{
		s = new Spawn(randomPosOnMap(), 1);
		s.setTarget(randomPosOnMap());
		s.color = randomColor();
		s.setId(i);
		g.addEntity(s);
	}
	
	//this sets things in motion
	gameLoop();
});

function randomPosOnMap()
{
	return new Position(randomBetween(0, ctx.canvas.width), randomBetween(0, ctx.canvas.height));
}

function getCursorPosition(e)
{
    var x;
    var y;
    if (e.pageX != undefined && e.pageY != undefined) {
	x = e.pageX;
	y = e.pageY;
    }
    else {
	x = e.clientX + document.body.scrollLeft +
            document.documentElement.scrollLeft;
	y = e.clientY + document.body.scrollTop +
            document.documentElement.scrollTop;
    }
    
	x -= c.offsetLeft;
    y -= c.offsetTop;
    
    return new Position(x, y);
}

function gameOnClick(e)
{
	var pos = getCursorPosition(e);
	g.click(pos);
}

function gameLoop(){
	g.run();

	timeout = setTimeout("gameLoop()", 1000/25);
}

//register foreach function on arrays
Array.prototype.foreach = function( callback ) {
	  for( var k=0; k<this .length; k++ ) {
	    callback( k, this[ k ] );
	  }
	}

//function to get random number upto m
function randomBetween(minVal,maxVal,floatVal)
{
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

function randomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}
